package bold.storage.util;

import bold.storage.core.DB;
import bold.storage.core.Record;
import bold.storage.core.RecordList;
import lombok.extern.log4j.Log4j2;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Log4j2
public class FilterUtil {
    private static Map<String, List<String>> cacheColumns = new HashMap<>();

    private FilterUtil() {
    }

    public static void init(String base) {
        new Thread(() -> {
            RecordList records = null;
            try {
                records = DB.query("select  table_name,GROUP_CONCAT(column_name) as column_name  from Information_schema" +
                        ".`columns`  where table_schema = ? and TABLE_NAME  not LIKE 'v_%' GROUP BY table_name", base);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            records.forEach(record -> {
                List<String> list = Arrays.asList(record.getString("column_name").split(","));
                cacheColumns.put(record.getString("table_name"), list);
            });
        }).start();
    }


    public static Map<String, String> filter(final Map<String, String> params, final String tableName) {
        Map<String, String> result = new HashMap<>();
        params.forEach((key, value) -> {
            if (cacheColumns.get(tableName).contains(key)) {
                result.put(key, value);
            }
        });
        return result;
    }


    public static Record filter(final Record params, final String tableName) {
        Record record = new Record();
        params.forEach((key, value) -> {
            if (cacheColumns.get(tableName).contains(key)) {
                record.set(key, value);
            }
        });
        return record;
    }

}
